package pod

import (
	"context"
	"fmt"
	"github.com/sirupsen/logrus"
	"k3s-api-test/pkg/utils"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/client-go/kubernetes"
	"time"
)

const (
	testNamespace = "default"       // 定义测试使用的命名空间
	testTimeout   = 1 * time.Minute // 单个测试用例的默认超时时间
	nodeName      = "agent1"        // 指定node节点名称
)

func RunPodTests(clientset *kubernetes.Clientset, log *logrus.Logger, selectedTestCase string) {
	log.Info("Starting Pods API tests...")

	// 运行具体的测试用例
	switch selectedTestCase {
	case "basic":
		runTestCase(clientset, log, "Basic_Pod_Creation_Deletion", testPodBasicCreationDeletion)
	case "container":
		runTestCase(clientset, log, "Pod_Containers_Fields", testPodContainersFields)
	case "field":
		runTestCase(clientset, log, "Pod_Fields", testPodFields)
	default:
		log.Warnf("No test case selected or invalid test case name '%s'. No tests will be executed. Available tests: basic, containers, pod.", selectedTestCase)
		// 这里不调用 runTestCase，也不做任何其他操作，直接返回
	}
	log.Info("This Pods API test completed.")
}

// runTestCase 是一个通用的测试用例执行器
func runTestCase(clientset *kubernetes.Clientset, log *logrus.Logger, name string, testFunc func(*kubernetes.Clientset, *logrus.Logger) error) {
	log.Infof("--- Running Test Case: %s ---", name)
	err := testFunc(clientset, log)
	if err != nil {
		log.Errorf("Test Case %s FAILED: %v", name, err)
	} else {
		log.Infof("Test Case %s PASSED", name)
	}
}

// testPodBasicCreationDeletion 测试Pod的基本创建和删除功能
// Ob:Name,Namespace,Labels;Spec:Containers;
func testPodBasicCreationDeletion(clientset *kubernetes.Clientset, log *logrus.Logger) error {
	podName := utils.GenerateUniqueName("basic-pod")
	testLabels := map[string]string{"test": "basic-creation"}

	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      podName,
			Namespace: testNamespace,
			Labels:    testLabels,
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name:  "nginx",
					Image: "jimlt.bfsmlt.top/nginx:test",
					Ports: []v1.ContainerPort{{ContainerPort: 80}},
				},
			},
		},
	}

	// defer 确保在函数返回前进行清理
	defer func() {
		log.Debugf("Cleaning up pod %s...", podName)
		err := utils.DeletePod(clientset, podName, testNamespace, log)
		if err != nil {
			log.Errorf("Failed to clean up pod %s: %v", podName, err)
		} else {
			log.Debugf("Pod %s cleaned up.", podName)
		}
	}()

	// 1. 创建 Pod
	createdPod, err := utils.CreatePod(clientset, pod, testNamespace, log)
	if err != nil {
		return fmt.Errorf("failed to create pod: %w", err)
	}
	log.Infof("CreatedPod name is %s", createdPod.Name)

	// 2. 验证 Pod 是否达到 Running 状态
	err = utils.WaitForPodPhase(clientset, createdPod.Name, testNamespace, v1.PodRunning, testTimeout, log)
	if err != nil {
		return fmt.Errorf("pod %s did not reach Running state: %w", createdPod.Name, err)
	}

	// 3. 验证 Pod 的 labels
	fetchedPod, err := clientset.CoreV1().Pods(testNamespace).Get(context.TODO(), createdPod.Name, metav1.GetOptions{})
	if err != nil {
		return fmt.Errorf("failed to get pod %s after creation: %w", createdPod.Name, err)
	}
	if fetchedPod.Labels["test"] != "basic-creation" {
		return fmt.Errorf("pod labels mismatch: expected 'test:basic-creation', got %v", fetchedPod.Labels)
	}

	log.Debugf("Pod %s successfully created and is running.", podName)
	return nil
}

// testPodContainersFields 测试Pod Containers中的各种字段
// Name,Image,Command,Args,Ports,ImagePullPolicy,Env,EnvFrom:ConfigMap,Resources,livenessProbe,readinessProbe
// startupProbe,LifeCycle 字段
func testPodContainersFields(clientset *kubernetes.Clientset, log *logrus.Logger) error {
	podName := utils.GenerateUniqueName("containers-fields")
	testLabels := map[string]string{"test": "containers-fields"}

	// 定义ConfigMap，用于EnvFromSource
	cmName := utils.GenerateUniqueName("test-configmap-for-env")
	configMap := &v1.ConfigMap{
		ObjectMeta: metav1.ObjectMeta{
			Name:      cmName,
			Namespace: testNamespace,
		},
		Data: map[string]string{
			"ENV_FROM_CM_KEY": "env_from_configmap_value",
		},
	}

	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      podName,
			Namespace: testNamespace,
			Labels:    testLabels,
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name:            "test-container",
					Image:           "jimlt.bfsmlt.top/nginx:test",
					Command:         []string{"sh", "-c"},
					Args:            []string{"echo Hello from container; sleep 3600"},
					ImagePullPolicy: v1.PullIfNotPresent,
					Ports: []v1.ContainerPort{
						{
							ContainerPort: 80, // Nginx 默认端口
							Name:          "http-test",
							Protocol:      v1.ProtocolTCP, // 默认 TCP

						},
					},
					// 容器中的环境变量
					Env: []v1.EnvVar{
						{Name: "MY_ENV_VAR", Value: "test_value"},
					},
					// EnvFromSource 表示一组 ConfigMaps 的来源
					EnvFrom: []v1.EnvFromSource{
						{
							ConfigMapRef: &v1.ConfigMapEnvSource{
								LocalObjectReference: v1.LocalObjectReference{Name: cmName},
								Optional:             utils.PtrBool(false), // 使用 utils.PtrBool
							},
						},
					},
					// 新增字段
					Resources: v1.ResourceRequirements{
						Limits: v1.ResourceList{
							v1.ResourceCPU:    resource.MustParse("200m"),
							v1.ResourceMemory: resource.MustParse("256Mi"),
						},
						Requests: v1.ResourceList{
							v1.ResourceCPU:    resource.MustParse("100m"),
							v1.ResourceMemory: resource.MustParse("128Mi"),
						},
					},
					LivenessProbe: &v1.Probe{
						ProbeHandler: v1.ProbeHandler{
							HTTPGet: &v1.HTTPGetAction{
								Path: "/index.html", // Nginx 默认静态文件
								Port: intstr.FromInt(80),
							},
						},
						InitialDelaySeconds: 5,
						PeriodSeconds:       5,
						TimeoutSeconds:      1,
						FailureThreshold:    3,
						SuccessThreshold:    1,
					},
					ReadinessProbe: &v1.Probe{
						ProbeHandler: v1.ProbeHandler{
							TCPSocket: &v1.TCPSocketAction{
								Port: intstr.FromInt(80), // 探测 80 端口是否可达
							},
						},
						InitialDelaySeconds: 10, // 启动后等待 10 秒开始第一次探测
						PeriodSeconds:       10, // 每隔 10 秒探测一次
						TimeoutSeconds:      1,
						FailureThreshold:    3,
					},
					// 用于处理启动时间较长的应用，避免LivenessProbe过早失败导致重启
					StartupProbe: &v1.Probe{
						ProbeHandler: v1.ProbeHandler{
							Exec: &v1.ExecAction{
								Command: []string{"cat", "/usr/share/nginx/html/index.html"}, // Nginx 默认文件路径
							},
						},
						InitialDelaySeconds: 0,  // 立即开始探测
						PeriodSeconds:       1,  // 每隔 1 秒探测一次
						FailureThreshold:    30, // 允许失败 30 次（即 30 秒）
						TimeoutSeconds:      1,
					},
					Lifecycle: &v1.Lifecycle{
						PostStart: &v1.LifecycleHandler{
							Exec: &v1.ExecAction{
								Command: []string{"/bin/sh", "-c", "echo PostStart hook executed > /tmp/poststart.log"},
							},
						},
						PreStop: &v1.LifecycleHandler{
							Exec: &v1.ExecAction{
								Command: []string{"/bin/sh", "-c", "echo PreStop hook executed > /tmp/prestop.log"},
							},
						},
					},
					// 容器安全上下文(可选)
				},
			},
			RestartPolicy: v1.RestartPolicyAlways,
			NodeSelector: map[string]string{
				"kubernetes.io/hostname": nodeName, // 使用定义的常量
			},
		},
	}

	defer func() {
		log.Debugf("Cleaning up pod %s...", podName)
		err := utils.DeletePod(clientset, podName, testNamespace, log) // 调用 utils.DeletePod
		if err != nil {
			log.Errorf("Failed to clean up pod %s: %v", podName, err)
		}
	}()
	// 1. 创建ConfigMap (用于EnvFromSource)
	_, err := clientset.CoreV1().ConfigMaps(testNamespace).Create(context.TODO(), configMap, metav1.CreateOptions{})
	if err != nil {
		return fmt.Errorf("failed to create configmap %s for envFrom: %w", cmName, err)
	}
	log.Infof("ConfigMap %s created for envFrom test.", cmName)

	createdPod, err := utils.CreatePod(clientset, pod, testNamespace, log) // 调用 utils.CreatePod
	if err != nil {
		return fmt.Errorf("failed to create pod: %w", err)
	}

	err = utils.WaitForPodPhase(clientset, createdPod.Name, testNamespace, v1.PodRunning, 10*time.Minute, log)
	if err != nil {
		return fmt.Errorf("pod %s did not reach Running state: %w", createdPod.Name, err)
	}

	fetchedPod, err := clientset.CoreV1().Pods(testNamespace).Get(context.TODO(), createdPod.Name, metav1.GetOptions{})
	if err != nil {
		return fmt.Errorf("failed to get pod %s: %w", createdPod.Name, err)
	}

	// 验证具体字段
	if len(fetchedPod.Spec.Containers) != 1 {
		return fmt.Errorf("expected 1 container, got %d", len(fetchedPod.Spec.Containers))
	}
	c := fetchedPod.Spec.Containers[0]

	// 验证基础字段
	if c.Name != "test-container" {
		return fmt.Errorf("container name mismatch: expected 'test-container', got '%s'", c.Name)
	}
	if c.Image != "jimlt.bfsmlt.top/nginx:test" {
		return fmt.Errorf("container image mismatch: expected 'jimlt.bfsmlt.top/nginx:test', got '%s'", c.Image)
	}
	//if len(c.Args) != 2 || c.Args[0] != "echo" || c.Args[1] != "Hello from container; sleep 3600" {
	//	return fmt.Errorf("container args mismatch: expected [echo Hello from container; sleep 3600], got %v", c.Args)
	// }
	if c.ImagePullPolicy != v1.PullIfNotPresent {
		return fmt.Errorf("image pull policy mismatch: expected '%s', got '%s'", v1.PullIfNotPresent, c.ImagePullPolicy)
	}
	if len(c.Ports) != 1 || c.Ports[0].ContainerPort != 80 || c.Ports[0].Name != "http-test" || c.Ports[0].Protocol != v1.ProtocolTCP {
		return fmt.Errorf("container ports mismatch: expected test port 80, got %v", c.Ports)
	}
	if len(c.Env) != 1 || c.Env[0].Name != "MY_ENV_VAR" || c.Env[0].Value != "test_value" {
		return fmt.Errorf("container env mismatch: expected MY_ENV_VAR=test_value, got %v", c.Env)
	}
	// 验证 EnvFrom
	if len(c.EnvFrom) != 1 || c.EnvFrom[0].ConfigMapRef == nil || c.EnvFrom[0].ConfigMapRef.Name != cmName || *c.EnvFrom[0].ConfigMapRef.Optional != false {
		return fmt.Errorf("container envFrom mismatch: expected ConfigMap %s, got %v", cmName, c.EnvFrom)
	}
	// 验证资源限制和请求
	if c.Resources.Limits.Cpu().String() != "200m" {
		return fmt.Errorf("CPU limits mismatch: expected 200m, got %s", c.Resources.Limits.Cpu().String())
	}
	if c.Resources.Limits.Memory().String() != "256Mi" {
		return fmt.Errorf("memory limits mismatch: expected 256Mi, got %s", c.Resources.Limits.Memory().String())
	}
	if c.Resources.Requests.Cpu().String() != "100m" {
		return fmt.Errorf("CPU requests mismatch: expected 100m, got %s", c.Resources.Requests.Cpu().String())
	}
	if c.Resources.Requests.Memory().String() != "128Mi" {
		return fmt.Errorf("memory requests mismatch: expected 128Mi, got %s", c.Resources.Requests.Memory().String())
	}
	// 验证探针
	if c.LivenessProbe == nil {
		return fmt.Errorf("liveness probe not set")
	}
	if c.LivenessProbe.InitialDelaySeconds != 5 || c.LivenessProbe.PeriodSeconds != 5 || c.LivenessProbe.TimeoutSeconds != 1 || c.LivenessProbe.FailureThreshold != 3 || c.LivenessProbe.SuccessThreshold != 1 {
		return fmt.Errorf("liveness probe parameters mismatch: got %+v", c.LivenessProbe)
	}
	if c.LivenessProbe.HTTPGet == nil || c.LivenessProbe.HTTPGet.Path != "/index.html" || c.LivenessProbe.HTTPGet.Port.IntVal != 80 {
		return fmt.Errorf("liveness probe HTTPGet mismatch: got %+v", c.LivenessProbe.HTTPGet)
	}

	if c.ReadinessProbe == nil {
		return fmt.Errorf("readiness probe not set")
	}
	if c.ReadinessProbe.InitialDelaySeconds != 10 || c.ReadinessProbe.PeriodSeconds != 10 { // 简化验证，可以更细致
		return fmt.Errorf("readiness probe parameters mismatch: got %+v", c.ReadinessProbe)
	}
	if c.ReadinessProbe.TCPSocket == nil || c.ReadinessProbe.TCPSocket.Port.IntVal != 80 {
		return fmt.Errorf("readiness probe TCPSocket mismatch: got %+v", c.ReadinessProbe.TCPSocket)
	}

	if c.StartupProbe == nil {
		return fmt.Errorf("startup probe not set")
	}
	if c.StartupProbe.PeriodSeconds != 1 || c.StartupProbe.FailureThreshold != 30 { // 简化验证
		return fmt.Errorf("startup probe parameters mismatch: got %+v", c.StartupProbe)
	}
	if c.StartupProbe.Exec == nil || len(c.StartupProbe.Exec.Command) != 2 || c.StartupProbe.Exec.Command[0] != "cat" || c.StartupProbe.Exec.Command[1] != "/usr/share/nginx/html/index.html" {
		return fmt.Errorf("startup probe Exec mismatch: got %+v", c.StartupProbe.Exec)
	}

	// --- 验证生命周期钩子 ---
	if c.Lifecycle == nil || c.Lifecycle.PostStart == nil || c.Lifecycle.PostStart.Exec == nil || len(c.Lifecycle.PostStart.Exec.Command) != 3 {
		return fmt.Errorf("postStart hook not set or command mismatch")
	}
	if c.Lifecycle.PostStart.Exec.Command[2] != "echo PostStart hook executed > /tmp/poststart.log" {
		return fmt.Errorf("postStart command content mismatch")
	}

	if c.Lifecycle.PreStop == nil || c.Lifecycle.PreStop.Exec == nil || len(c.Lifecycle.PreStop.Exec.Command) != 3 {
		return fmt.Errorf("preStop hook not set or command mismatch")
	}
	if c.Lifecycle.PreStop.Exec.Command[2] != "echo PreStop hook executed > /tmp/prestop.log" {
		return fmt.Errorf("preStop command content mismatch")
	}

	if fetchedPod.Spec.RestartPolicy != v1.RestartPolicyAlways {
		return fmt.Errorf("restart policy mismatch: expected '%s', got '%s'", v1.RestartPolicyAlways, fetchedPod.Spec.RestartPolicy)
	}
	if fetchedPod.Spec.NodeSelector["kubernetes.io/hostname"] != nodeName {
		return fmt.Errorf("node selector mismatch: expected hostname '%s', got %s", nodeName, fetchedPod.Spec.NodeSelector["kubernetes.io/hostname"])
	}

	log.Debugf("Pod %s container fields verified successfully.", podName)
	return nil
}

// 测试 Pod 的所有字段
func testPodFields(clientset *kubernetes.Clientset, log *logrus.Logger) error {
	podName := utils.GenerateUniqueName("testpod")
	testLabels := map[string]string{"test": "advanced-fields"}
	cmName := utils.GenerateUniqueName("test-configmap")
	serviceAccountName := utils.GenerateUniqueName("test-sa")

	// 1.创建ServiceAccount
	sa := &v1.ServiceAccount{
		ObjectMeta: metav1.ObjectMeta{
			Name:      serviceAccountName,
			Namespace: testNamespace,
		},
	}
	_, err := clientset.CoreV1().ServiceAccounts(testNamespace).Create(context.TODO(), sa, metav1.CreateOptions{})
	if err != nil {
		return fmt.Errorf("failed to create ServiceAccount %s: %w", serviceAccountName, err)
	}
	log.Infof("ServiceAccount %s created.", serviceAccountName)

	// 2.创建一个ConfigMap 供 Pod 使用
	configMap := &v1.ConfigMap{
		ObjectMeta: metav1.ObjectMeta{
			Name:      cmName,
			Namespace: testNamespace,
		},
		Data: map[string]string{
			"config.txt": "This is a test config file.",
		},
	}
	_, err = clientset.CoreV1().ConfigMaps(testNamespace).Create(context.TODO(), configMap, metav1.CreateOptions{})
	if err != nil {
		return fmt.Errorf("failed to create ConfigMap %s: %w", cmName, err)
	}
	log.Infof("ConfigMap %s created.", cmName)

	// 声明 Pod 配置
	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      podName,
			Namespace: testNamespace,
			Labels:    testLabels,
			Annotations: map[string]string{
				"imageRegistry": "https://jimlt.bfsmlt.top",
			},
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name:    "test-container",
					Image:   "jimlt.bfsmlt.top/busybox:v1.0",
					Command: []string{"sh", "-c", "cat /etc/config/config.txt; sleep 3600"},
					VolumeMounts: []v1.VolumeMount{
						{
							Name:      "config-volume",
							MountPath: "/etc/config",
						},
					},
				},
			},
			// Pod 级别的字段
			Volumes: []v1.Volume{
				{
					Name: "config-volume",
					VolumeSource: v1.VolumeSource{
						ConfigMap: &v1.ConfigMapVolumeSource{
							LocalObjectReference: v1.LocalObjectReference{
								Name: cmName,
							},
						},
					},
				},
				{
					Name: "host-path-volume",
					VolumeSource: v1.VolumeSource{
						HostPath: &v1.HostPathVolumeSource{
							Path: "/tmp/k8s-test-hostpath",
							Type: utils.Ptr(v1.HostPathDirectoryOrCreate),
						},
					},
				},
			},
			// 调度相关
			NodeSelector: map[string]string{
				"kubernetes.io/hostname": nodeName,
			},
			Affinity: &v1.Affinity{
				NodeAffinity: &v1.NodeAffinity{
					PreferredDuringSchedulingIgnoredDuringExecution: []v1.PreferredSchedulingTerm{
						{
							Weight: 100,
							Preference: v1.NodeSelectorTerm{
								MatchExpressions: []v1.NodeSelectorRequirement{
									{
										Key:      "disktype",
										Operator: v1.NodeSelectorOpIn,
										Values:   []string{"ssd"},
									},
								},
							},
						},
					},
				},
			},
			// 容忍度相关,为什么这里长度和容量都是4？
			Tolerations: []v1.Toleration{
				{
					Key:      "example-taint",
					Operator: v1.TolerationOpExists,
					Effect:   v1.TaintEffectNoSchedule,
				},
				{
					Key:      "key1",
					Operator: v1.TolerationOpEqual,
					Effect:   v1.TaintEffectNoSchedule,
				},
			},
			// 生命周期
			RestartPolicy: v1.RestartPolicyOnFailure, // 容器失败时才会重启pod
		},
	}

	defer func() {
		log.Debugf("Cleaning up ConfigMap %s...", cmName)
		err := clientset.CoreV1().ConfigMaps(testNamespace).Delete(context.TODO(), cmName, metav1.DeleteOptions{})
		if err != nil && !errors.IsNotFound(err) {
			log.Errorf("Failed to clean up ConfigMap %s: %v", cmName, err)
		}

		log.Debugf("Cleaning up pod %s...", podName)
		err = utils.DeletePod(clientset, podName, testNamespace, log)
		if err != nil {
			log.Errorf("Failed to clean up pod %s: %v", podName, err)
		}
		log.Debugf("Cleaning up ConfigMap %s...", cmName)
		err = clientset.CoreV1().ConfigMaps(testNamespace).Delete(context.TODO(), cmName, metav1.DeleteOptions{})
		if err != nil && !errors.IsNotFound(err) {
			log.Errorf("Failed to clean up ConfigMap %s: %v", cmName, err)
		}

		log.Debugf("Cleaning up ServiceAccount %s...", serviceAccountName)
		err = clientset.CoreV1().ServiceAccounts(testNamespace).Delete(context.TODO(), serviceAccountName, metav1.DeleteOptions{})
		if err != nil && !errors.IsNotFound(err) {
			log.Errorf("Failed to clean up ServiceAccount %s: %v", serviceAccountName, err)
		}
	}()

	createdPod, err := utils.CreatePod(clientset, pod, testNamespace, log)
	if err != nil {
		return fmt.Errorf("failed to create pod: %w", err)
	}
	log.Infof("CreatedPod name is %s", createdPod.Name)

	err = utils.WaitForPodPhase(clientset, createdPod.Name, testNamespace, v1.PodRunning, testTimeout, log)
	if err != nil {
		return fmt.Errorf("pod %s did not reach Running state: %w", createdPod.Name, err)
	}
	fetchedPod, err := clientset.CoreV1().Pods(testNamespace).Get(context.TODO(), createdPod.Name, metav1.GetOptions{})
	if err != nil {
		return fmt.Errorf("failed to get pod %s: %w", createdPod.Name, err)
	}

	// 验证Pod添加的字段
	log.Infof("NameSpace matched: %s", fetchedPod.Namespace)
	// 验证 Labels 和 Annotations
	if fetchedPod.Labels["test"] != "advanced-fields" {
		return fmt.Errorf("pod labels mismatch: expected 'test:advanced-fields', got %v", fetchedPod.Labels)
	}
	log.Infof("pod labels matched: %v", fetchedPod.Labels)
	if fetchedPod.Annotations["imageRegistry"] != "https://jimlt.bfsmlt.top" {
		return fmt.Errorf("pod annotations mismatch: expected 'https://jimlt.bfsmlt.top', got %v", fetchedPod.Annotations)
	}
	log.Infof("pod annotations matched: %v", fetchedPod.Annotations)
	// 验证 Volumes
	if len(fetchedPod.Spec.Volumes) != 3 {
		return fmt.Errorf("expected 3 volumes, got %d", len(fetchedPod.Spec.Volumes))
	}
	log.Infof("pod Volumes matched: %v", fetchedPod.Spec.Volumes)
	// 验证 config-volume
	cmVolumeFound := false
	for _, vol := range fetchedPod.Spec.Volumes {
		if vol.Name == "config-volume" {
			if vol.ConfigMap == nil || vol.ConfigMap.Name != cmName {
				return fmt.Errorf("config-volume mismatch: expected ConfigMap %s, got %v", cmName, vol.ConfigMap)
			}
			cmVolumeFound = true
		}
	}
	if !cmVolumeFound {
		return fmt.Errorf("config-volume not found")
	}
	// 验证 host-path-volume
	hostPathVolumeFound := false
	for _, vol := range fetchedPod.Spec.Volumes {
		if vol.Name == "host-path-volume" {
			if vol.HostPath == nil || vol.HostPath.Path != "/tmp/k8s-test-hostpath" || *vol.HostPath.Type != v1.HostPathDirectoryOrCreate {
				return fmt.Errorf("host-path-volume mismatch: expected path /tmp/k8s-test-hostpath and type DirectoryOrCreate, got %+v", vol.HostPath)
			}
			hostPathVolumeFound = true
		}
	}
	if !hostPathVolumeFound {
		return fmt.Errorf("host-path-volume not found")
	}

	// 验证 NodeSelector
	if fetchedPod.Spec.NodeSelector["kubernetes.io/hostname"] != nodeName {
		return fmt.Errorf("node selector mismatch: expected hostname '%s', got '%s'", nodeName, fetchedPod.Spec.NodeSelector["kubernetes.io/hostname"])
	}
	log.Infof("node selector matched %s", fetchedPod.Spec.NodeSelector["kubernetes.io/hostname"])

	// 验证 Affinity (仅简单检查是否存在，复杂匹配需深度比较)
	if fetchedPod.Spec.Affinity == nil || fetchedPod.Spec.Affinity.NodeAffinity == nil ||
		len(fetchedPod.Spec.Affinity.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution) != 1 {
		return fmt.Errorf("node affinity mismatch or not set")
	}
	log.Infof("node affinity matched")
	if fetchedPod.Spec.Affinity.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution[0].Weight != 100 ||
		len(fetchedPod.Spec.Affinity.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution[0].Preference.MatchExpressions) != 1 ||
		fetchedPod.Spec.Affinity.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution[0].Preference.MatchExpressions[0].Key != "disktype" {
		return fmt.Errorf("node affinity details mismatch")
	}

	// 验证 Tolerations
	// 为什么这里长度会输出为4？Tolerations是一个 Toleration类型的切片，Toleration类型是一个结构体，我声明了两个{},应该是2才对啊
	// 是不是因为声明的时候，是[]int这样声明，然后里面直接写了两个，这样扩容两次，长度和容量就是4？
	//if len(fetchedPod.Spec.Tolerations) != 2 {
	//	return fmt.Errorf("expected 2 toleration, got %d", len(fetchedPod.Spec.Tolerations))
	//}
	log.Infof("Tolerations length is %d, cap is %d", len(fetchedPod.Spec.Tolerations), cap(fetchedPod.Spec.Tolerations))
	t := fetchedPod.Spec.Tolerations[0]
	if t.Key != "example-taint" || t.Operator != v1.TolerationOpExists || t.Effect != v1.TaintEffectNoSchedule {
		return fmt.Errorf("toleration mismatch: expected example-taint, Exists, NoSchedule, got %+v", t)
	}
	log.Infof("toleration matched: got %+v", t)
	// 验证 RestartPolicy
	if fetchedPod.Spec.RestartPolicy != v1.RestartPolicyOnFailure {
		return fmt.Errorf("restart policy mismatch: expected '%s', got '%s'", v1.RestartPolicyOnFailure, fetchedPod.Spec.RestartPolicy)
	}
	log.Infof("restart policy matched: '%s'", fetchedPod.Spec.RestartPolicy)
	log.Debugf("Pod %s all fileds verified successfully.", podName)
	return nil
}
